package app.nexd.com.indoor.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import java.util.ArrayList;
import java.util.List;

import app.nexd.com.indoor.R;
import app.nexd.com.indoor.activity.inter.IBDMapViewActivity;
import app.nexd.com.indoor.mode.CityModel;
import app.nexd.com.indoor.mode.MallModel;
import app.nexd.com.indoor.presenter.IBDMapViewPresenterImpl;
import app.nexd.com.indoor.presenter.inter.IBDMapViewPresenter;

public class BDMapViewActivity extends Activity implements IBDMapViewActivity, View.OnClickListener {
    private static final int CITY = 10001;
    public static final int CITY_RESULT = 10002;
    private MapView mMapView;
    private IBDMapViewPresenter ibdMapViewPresenter;
    private BaiduMap baiduMap;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private TextView cityName;
    private RelativeLayout city_layout;
    private MallModel mallModel;
    private ArrayList<CityModel> citys;
    private LatLng currentLocationLatLng;
    private List<Overlay> mallOverlays;
    private List<Overlay> planningOverlays;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_column);
        setContentView(R.layout.activity_main);
        cityName = (TextView) this.findViewById(R.id.city_name);
        city_layout = (RelativeLayout) this.findViewById(R.id.city_layout);
        city_layout.setOnClickListener(this);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.showZoomControls(false);
        mMapView.showScaleControl(false);

        // 初始化存储图层的集合
        mallOverlays = new ArrayList<>();
        planningOverlays = new ArrayList<>();
        ibdMapViewPresenter = new IBDMapViewPresenterImpl(getApplicationContext(), this, mMapView);

        baiduMap = mMapView.getMap();
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        citys = getIntent().getParcelableArrayListExtra("citys");

        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
        baiduMap.setMyLocationEnabled(true); // 开启定位图层
        baiduMap.setBuildingsEnabled(false); // 设置建筑是否可见

        ibdMapViewPresenter.initMap();

        if (citys != null && citys.size() != 0) {
            ibdMapViewPresenter.requestAllMalls(citys.get(0).getCityCode());
            setCityCenter(citys.get(0).getCenterLatLng());
        } else {
            showToast("数据异常，请检查网络！");
        }
        ibdMapViewPresenter.startLocation();

        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {

                mallModel = marker.getExtraInfo().getParcelable("MallModel");
                setBDMapCenter(mallModel.getLatLng());
                View popuView = LayoutInflater.from(BDMapViewActivity.this).inflate(R.layout.info_window, null);
                LinearLayout layout = (LinearLayout) popuView.findViewById(R.id.intoMall);
                TextView mallName = (TextView) popuView.findViewById(R.id.mallName);
                ImageButton gotoThere = (ImageButton) popuView.findViewById(R.id.goToThere);
                mallName.setText(mallModel.getName());
                layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ibdMapViewPresenter.enterNexdMap(BDMapViewActivity.this, mallModel);
                    }
                });
                gotoThere.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(BDMapViewActivity.this, RoutePlanActivity.class);
                        intent.putExtra("start", currentLocationLatLng);
                        intent.putExtra("end", mallModel.getLatLng());
                        BDMapViewActivity.this.startActivity(intent);
                    }
                });
                InfoWindow infoWindow = new InfoWindow(popuView, mallModel.getLatLng(), 10);
                baiduMap.showInfoWindow(infoWindow);
                return false;
            }
        });

        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                baiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    private void setCityCenter(LatLng latLng) {
        Log.d("setCityCenter", "removeMallOverlay");
        baiduMap.clear();
        setBDMapCenter(latLng);
    }

    // 设置百度地图城市中心点
    private void setBDMapCenter(LatLng latLng) {
        //定义地图状态
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(latLng, 13);
        //改变地图状态
        animateMapStatus(mMapStatusUpdate);
//        baiduMap.setMapStatus(mMapStatusUpdate);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        ibdMapViewPresenter.stopLocation();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
        super.onPause();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == CITY_RESULT) {
            CityModel cityModel = data.getParcelableExtra("city");
            cityName.setText(cityModel.getCityName());
            setCityCenter(cityModel.getCenterLatLng());
            ibdMapViewPresenter.requestAllMalls(cityModel.getCityCode());
            baiduMap.hideInfoWindow();
        }
    }

    @Override
    protected void onStop() {
        ibdMapViewPresenter.stopLocation();
        super.onStop();
    }

    @Override
    public void setLocationData(MyLocationData locationData) {
        currentLocationLatLng = new LatLng(locationData.latitude, locationData.longitude);
        baiduMap.setMyLocationData(locationData);
    }

    @Override
    public void addOverlay(OverlayOptions options) {
        mallOverlays.add(baiduMap.addOverlay(options));
    }

    @Override
    public void animateMapStatus(MapStatusUpdate mapStatusUpdate) {
        baiduMap.animateMapStatus(mapStatusUpdate);
    }

    @Override
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.city_layout:
                Intent intent = new Intent(BDMapViewActivity.this, CityListActivity.class);
                intent.putParcelableArrayListExtra("citys", citys);
                BDMapViewActivity.this.startActivityForResult(intent, CITY);
                break;
        }
    }
}
